<template>
  <div class="login-back">
    <span class="login-head-link">
      <img src="@/assets/logo.png" style="height: 60px" />
    </span>
    <img src="@/assets/background.png" class="register-image-background" />
    <el-card class="login-card" shadow="never" v-if="resetPasswordShow">
      <el-form ref="confirmLoginForm" :model="confirmForm" :rules="loginRules">
        <el-form-item class="login-title-item">
          <span class="form-title">{{ VITE_APP_SYSTEM_NAME }}</span>
        </el-form-item>
        <el-form-item prop="oldPassword" required>
          <el-input type="password" style="position: fixed; bottom: -9999px" />
          <el-input
            v-model="confirmForm.oldPassword"
            :type="passwordType"
            autocomplete="new-password"
            placeholder="请输入旧密码"
          >
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword" required>
          <el-input type="password" style="position: fixed; bottom: -9999px" />
          <el-input
            v-model="confirmForm.newPassword"
            :type="passwordType"
            autocomplete="new-password"
            placeholder="请输入新密码"
          >
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" required>
          <el-input type="password" style="position: fixed; bottom: -9999px" />
          <el-input
            v-model="confirmForm.confirmPassword"
            :type="passwordType"
            autocomplete="new-password"
            placeholder="请输入确认密码"
          >
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" class="login-kaptcha" required>
          <el-input
            v-model="confirmForm.code"
            placeholder="请输入验证码"
            autocomplete="off"
          />
          <img :src="kaptchaUrl" @click="kaptchaRefresh" />
        </el-form-item>
        <el-form-item class="login-forget">
          <span class="login-link" @click="forget"> 忘记密码 </span>
        </el-form-item>
        <el-form-item style="margin-top: 5px">
          <input
            type="button"
            value="登录"
            @click="resetPassword"
            style="width: 100%"
            class="login-submit"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="login-card" shadow="never" v-else>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
        <el-form-item class="login-title-item">
          <span class="form-title">{{ VITE_APP_SYSTEM_NAME }}</span>
        </el-form-item>
        <el-form-item prop="userName" required>
          <el-input
            v-model="loginForm.userName"
            placeholder="请输入用户名"
            type="text"
          />
        </el-form-item>
        <el-form-item prop="password" required>
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item prop="code" class="login-kaptcha" required>
          <el-input v-model="loginForm.code" placeholder="请输入验证码" />
          <img :src="kaptchaUrl" @click="kaptchaRefresh" />
        </el-form-item>
        <el-form-item class="login-forget">
          <span class="login-link" @click="forget"> 忘记密码 </span>
        </el-form-item>
        <el-form-item style="margin-top: 5px">
          <input
            type="button"
            value="登录"
            @click="handleLogin"
            style="width: 100%"
            class="login-submit"
          />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="account-foot-copyright">
      <span>{{ VITE_APP_COPYRIGHT }}</span>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { login, updatePwdCheck } from '@/api/login';
import { paperEncrypt, rsaEncryptStr } from '@/utils';
import { v4 } from 'uuid';
import useStore from '@/store';
import router from '@/router';

const { user } = useStore();

export default {
  name: 'Login',
  data() {
    const EqualsPassword = (rule, value, callback) => {
      if (this.confirmForm.newPassword != value) {
        callback(new Error('密码不一致'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      var rule1 = new RegExp('(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,18}');
      var rule2 = new RegExp(this.loginForm.userName, 'i');
      // 规则三：密码中需要进行敏感词过滤
      var sensitiveWords = /shensi|sdses|jnny|jnrl|jnrd|sdgh|nygc|ntjt|cszm/i;
      if (!rule1.test(value)) {
        callback(
          new Error(
            '密码需由8-20位数字、大写字母、小写字母 、特殊字符组合而成。'
          )
        );
      } else if (rule2.test(value)) {
        callback(new Error('密码中不能包含用户名'));
      } else if (this.confirmForm.oldPassword === value) {
        callback(new Error('新密码不能与旧密码一致'));
      } else if (sensitiveWords.test(value)) {
        callback(
          new Error(
            '密码中需要进行敏感词过滤 （忽略大小写，shensi、sdses、jnny、jnrl、jnrd、sdgh、nygc、ntjt、cszm）。'
          )
        );
      } else {
        callback();
      }
    };
    return {
      resetPasswordShow: false, //显示重置密码页面
      VITE_APP_SYSTEM_NAME: import.meta.env.VITE_APP_SYSTEM_NAME,
      VITE_APP_COPYRIGHT: import.meta.env.VITE_APP_COPYRIGHT,
      kaptchaUrl: '/pxks-api/kaptcha/refresh',
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = '';
        } else {
          this.passwordType = 'password';
        }
        this.$nextTick(() => {
          this.$refs.password.focus();
        });
      },
      //登录表单
      loginForm: {
        userName: '',
        password: '',
        codeKey: null,
        code: null
      },
      //重置密码表单
      confirmForm: {
        oldPassword: null,
        newPassword: null,
        confirmPassword: null,
        codeKey: null,
        code: null
      },
      passwordType: 'password',
      loginRules: {
        userName: [{ required: true, message: '请输入用户名' }],
        password: [
          { required: true, message: '请输入密码' },
          { min: 8, max: 18, message: '密码长度在8到18个字符之间' }
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { min: 4, max: 4, message: '长度为 4 个字符' }
        ],
        oldPassword: [
          { required: true, trigger: 'blur', message: '密码不能为空' }
        ],
        newPassword: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
          { validator: EqualsPassword, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.kaptchaRefresh();
  },
  methods: {
    kaptchaRefresh() {
      let uuidKey = v4().toString();
      this.loginForm.codeKey = uuidKey;
      this.kaptchaUrl = `/pxks-api/kaptcha/refresh?code=${uuidKey}`;
    },
    getLogin() {
      this.$refs.loginForm.validate(valid => {
        let that = this;
        if (valid) {
          login(
            paperEncrypt(
              import.meta.env.VITE_APP_PAIR_ONE_PUBLIC_KEY,
              this.loginForm
            )
          ).then(function (re) {
            if (re && re.code === 1) {
              localStorage.clear();
              user.login(re.response);
              router.push({ path: '/' }).catch(err => {});
            } else if (re.code === 20 || re.code === 30) {
              that.resetPasswordShow = true;
              ElMessage.success(re.message);
            } else {
              ElMessage.error(re.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    handleLogin() {
      this.getLogin();
    },
    //重置密码
    async resetPassword() {
      this.$refs.confirmLoginForm.validate(async valid => {
        if (valid) {
          try {
            let params = {
              userName: this.loginForm.userName,
              oldPassword: rsaEncryptStr(
                import.meta.env.VITE_APP_PAIR_ONE_PUBLIC_KEY,
                this.confirmForm.oldPassword
              ),
              newPassword: rsaEncryptStr(
                import.meta.env.VITE_APP_PAIR_ONE_PUBLIC_KEY,
                this.confirmForm.newPassword
              ),
              confirmPassword: rsaEncryptStr(
                import.meta.env.VITE_APP_PAIR_ONE_PUBLIC_KEY,
                this.confirmForm.confirmPassword
              )
            };
            const res = await updatePwdCheck(params);
            if (res.code === 1) {
              this.$message.success(res.message);
              this.resetPasswordShow = false;
            } else {
              this.$message.error(res.message);
            }
          } catch (error) {
            console.log(error, 'error');
          }
        }
      });
    },
    forget() {
      ElMessage.warning('请联系管理员');
    }
  }
};
</script>
